package com.freedom.start.sys.service;

import com.freedom.start.sys.dao.OrgDao;
import com.freedom.start.sys.entity.OrgEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhenggang.liu
 * @Date: 2020/2/4 1:23
 */

@Service
@Async("asyncExecutor")
public class AsyncService {

    @Autowired
    OrgDao orgDao;

    /**
     * 批量更新子机构的机构ids
     * @param orgEntity 被修改的父机构
     */
    public void updateOrgParentIds(OrgEntity orgEntity) {
        //查找所有机构
        List<OrgEntity> allOrg = orgDao.findAll();
        ArrayList<OrgEntity> parentOrgList = new ArrayList<>();
        ArrayList<OrgEntity> childOrgList = new ArrayList<>();
        parentOrgList.add(orgEntity);
        getChildOrg(allOrg, parentOrgList, childOrgList);
        orgDao.batchUpdate(childOrgList);

    }

    /**
     * 递归获取修改的机构的后代子机构，同时修改子机构的层级和id路径
     *
     * @param allOrg 所有机构
     * @param parentOrgList 父机构列表，每次递归都会重置
     * @param childOrgList 子机构列表，每次递归是累加的，不会重置
     * @return
     */
    private List<OrgEntity> getChildOrg(List<OrgEntity> allOrg, List<OrgEntity> parentOrgList, List<OrgEntity> childOrgList) {
        List<OrgEntity> tempParentOrg = new ArrayList<>();
        for (OrgEntity parentOrg : parentOrgList) {
            for (OrgEntity org : allOrg) {
                if (parentOrg.getId().equalsIgnoreCase(org.getParentId())) {
                    org.setLevel(parentOrg.getLevel() + 1);
                    org.setOrgIds(parentOrg.getOrgIds() + "," + org.getId());
                    childOrgList.add(org);
                    tempParentOrg.add(org);
                }
            }
        }
        if (tempParentOrg != null && tempParentOrg.size() > 0) {
            getChildOrg(allOrg, tempParentOrg, childOrgList);
        }

        return childOrgList;
    }
}
